import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface WorkOrderProcessingData {
  workOrderId: string
  startTime: string
  endTime?: string
  description: string
  photos: string[]
  materialsUsed?: string[]
  issuesFound?: string[]
  recommendations?: string[]
  technicianSignature?: string
  clientSignature?: string
}

export interface WorkOrderReview {
  workOrderId: string
  clientId: string
  clientName: string
  rating: number // 1-5 stars
  comment: string
  photos?: string[]
  createdAt: string
  helpful?: boolean
}

export interface ProcessingValidation {
  isValid: boolean
  errors: string[]
}

export const useWorkOrderProcessStore = defineStore('workOrderProcess', () => {
  // 当前处理的数据
  const currentProcess = ref<WorkOrderProcessingData | null>(null)
  const processingPhotos = ref<string[]>([])
  const processingDescription = ref('')
  const isProcessing = ref(false)

  // 客户评价数据
  const workOrderReviews = ref<WorkOrderReview[]>([])

  // 验证处理数据
  const validateProcessingData = (description: string, photos: string[]): ProcessingValidation => {
    const errors: string[] = []

    // 检查描述长度
    if (description.length < 20) {
      errors.push('处理描述至少需要20个字符')
    }

    // 检查照片数量
    if (photos.length < 2) {
      errors.push('至少需要上传2张照片作为处理证据')
    }

    // 检查照片内容（基本验证）
    const validPhotos = photos.filter(photo => photo && photo.length > 0)
    if (validPhotos.length < 2) {
      errors.push('请确保上传的照片有效')
    }

    return {
      isValid: errors.length === 0,
      errors
    }
  }

  // 开始处理工单
  const startProcessing = async (workOrderId: string): Promise<boolean> => {
    try {
      isProcessing.value = true

      // 初始化处理数据
      currentProcess.value = {
        workOrderId,
        startTime: new Date().toLocaleString('zh-CN'),
        description: '',
        photos: []
      }

      processingDescription.value = ''
      processingPhotos.value = []

      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500))

      return true
    } catch (error) {
      console.error('开始处理工单失败:', error)
      return false
    } finally {
      isProcessing.value = false
    }
  }

  // 添加处理照片
  const addProcessingPhoto = (photoPath: string): void => {
    if (processingPhotos.value.length < 10) { // 最多10张照片
      processingPhotos.value.push(photoPath)
    }
  }

  // 删除处理照片
  const removeProcessingPhoto = (index: number): void => {
    processingPhotos.value.splice(index, 1)
  }

  // 上传处理照片
  const uploadProcessingPhotos = async (): Promise<string[]> => {
    try {
      // 模拟上传过程
      const uploadedPhotos: string[] = []

      for (let i = 0; i < processingPhotos.value.length; i++) {
        await new Promise(resolve => setTimeout(resolve, 300))
        uploadedPhotos.push(processingPhotos.value[i])
      }

      return uploadedPhotos
    } catch (error) {
      console.error('上传处理照片失败:', error)
      throw error
    }
  }

  // 完成工单处理
  const completeProcessing = async (
    workOrderId: string,
    description: string,
    photos: string[],
    additionalData?: {
      materialsUsed?: string[]
      issuesFound?: string[]
      recommendations?: string[]
    }
  ): Promise<boolean> => {
    try {
      // 验证数据
      const validation = validateProcessingData(description, photos)
      if (!validation.isValid) {
        throw new Error(validation.errors.join('；'))
      }

      isProcessing.value = true

      // 上传照片
      const uploadedPhotos = await uploadProcessingPhotos()

      // 构建处理数据
      const processingData: WorkOrderProcessingData = {
        workOrderId,
        startTime: currentProcess.value?.startTime || new Date().toLocaleString('zh-CN'),
        endTime: new Date().toLocaleString('zh-CN'),
        description,
        photos: uploadedPhotos,
        ...additionalData
      }

      // 模拟API调用保存处理数据
      await new Promise(resolve => setTimeout(resolve, 1000))

      // 更新当前处理数据
      currentProcess.value = processingData

      return true
    } catch (error) {
      console.error('完成工单处理失败:', error)
      throw error
    } finally {
      isProcessing.value = false
    }
  }

  // 提交客户评价
  const submitClientReview = async (review: Omit<WorkOrderReview, 'createdAt'>): Promise<boolean> => {
    try {
      const fullReview: WorkOrderReview = {
        ...review,
        createdAt: new Date().toLocaleString('zh-CN')
      }

      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500))

      workOrderReviews.value.unshift(fullReview)

      return true
    } catch (error) {
      console.error('提交客户评价失败:', error)
      throw error
    }
  }

  // 获取工单评价
  const getWorkOrderReviews = (workOrderId: string): WorkOrderReview[] => {
    return workOrderReviews.value.filter(review => review.workOrderId === workOrderId)
  }

  // 获取平均评分
  const getAverageRating = (workOrderId: string): number => {
    const reviews = getWorkOrderReviews(workOrderId)
    if (reviews.length === 0) return 0

    const totalRating = reviews.reduce((sum, review) => sum + review.rating, 0)
    return Math.round((totalRating / reviews.length) * 10) / 10
  }

  // 清理当前处理数据
  const clearCurrentProcess = (): void => {
    currentProcess.value = null
    processingDescription.value = ''
    processingPhotos.value = []
  }

  return {
    // 状态
    currentProcess,
    processingPhotos,
    processingDescription,
    isProcessing,
    workOrderReviews,

    // 计算属性

    // 方法
    validateProcessingData,
    startProcessing,
    addProcessingPhoto,
    removeProcessingPhoto,
    uploadProcessingPhotos,
    completeProcessing,
    submitClientReview,
    getWorkOrderReviews,
    getAverageRating,
    clearCurrentProcess
  }
})